package pers.cyril.jdb.client.sender;

import com.beust.jcommander.JCommander;
import io.netty.channel.Channel;
import pers.cyril.jdb.client.command.CreateCommand;
import pers.cyril.jdb.client.command.SQLCommand;
import pers.cyril.jdb.client.command.UseCommand;
import pers.cyril.jdb.client.command.handler.CommandHandlerManager;

import java.util.Scanner;

/**
 * 说点什么吧
 *
 * @author Wang Cyril
 * @date 2024/5/20 19:14
 */
public class ConsoleScriptSender implements ConsoleCommandSender {

    public static final ConsoleScriptSender INSTANCE = new ConsoleScriptSender();

    private Scanner scanner = new Scanner(System.in);

    public ConsoleScriptSender() {

    }

    @Override
    public void send(Channel channel) {
        boolean success = false;
        while (!success) {
            String script = scanner.nextLine();
            try {
                CreateCommand createCommand = new CreateCommand();
                UseCommand useCommand = new UseCommand();
                SQLCommand sqlCommand = new SQLCommand();
                JCommander jc = JCommander.newBuilder()
                        .programName("jdb")
                        .addCommand(createCommand)
                        .addCommand(useCommand)
                        .addCommand(sqlCommand)
                        .build();
                jc.parse(script.split("\\s+"));

                switch (jc.getParsedCommand()) {
                    case "create":
                        CommandHandlerManager.getHandler(CreateCommand.class).handle(createCommand, channel);
                        success = true;
                        break;
                    case "use":
                        CommandHandlerManager.getHandler(UseCommand.class).handle(useCommand, channel);
                        success = true;
                        break;
                    default:
                        CommandHandlerManager.getHandler(SQLCommand.class).handle(sqlCommand, channel);
                        success = true;
                        break;
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
